package com.atguigu.petstore.sys.minio.config;

import com.atguigu.petstore.sys.minio.config.properties.MinioProperties;
import io.minio.BucketExistsArgs;
import io.minio.MakeBucketArgs;
import io.minio.MinioClient;
import io.minio.errors.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.io.IOException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;

/**
 * @author lfy
 * @Description
 * @create 2023-09-23 9:08
 */
@Configuration
public class MinioConfiguration {


    @Autowired
   MinioProperties minioProperties;

    @Bean
    public MinioClient minioClient() throws ServerException, InsufficientDataException, ErrorResponseException, IOException, NoSuchAlgorithmException, InvalidKeyException, InvalidResponseException, XmlParserException, InternalException {
        MinioClient client = MinioClient.builder()
                .endpoint(minioProperties.getEndpoint())
                .credentials(minioProperties.getAccessKey(),
                        minioProperties.getAccessSecret())
                .build();

        BucketExistsArgs args = BucketExistsArgs.builder()
                .bucket(minioProperties.getBucket())
                .build();

        //如果没有指定桶，就建造
        boolean exists = client.bucketExists(args);
        if(!exists){
            MakeBucketArgs bucketArgs = MakeBucketArgs.builder()
                    .bucket(minioProperties.getBucket())
                    .build();
            client.makeBucket(bucketArgs);
        }
        return client;
    }
}
